package controllers;

import static play.data.Form.form;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import models.Chapitre;
import models.Choix;
import models.Matiere;
import models.NiveauQuestion;
import models.Qcm;
import models.QcmNiveauQuestion;
import models.Question;
import models.Theme;
import models.User;

import play.Logger;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http.Session;
import play.mvc.Result;

import views.html.CreateQCM.*;

public class CreateQCM extends Controller {

	/**
	 * Navigation entre les étapes. On sauvegarde le qcm dans la session
	 */
	public static Result step(int step) {
		try {
			Qcm qcm = toQcm(session());
			Form<Qcm> qcmForm = form(Qcm.class).fill(qcm);
			String dateOuverture = null;
			String dateFermeture = null;
			GregorianCalendar cal = new GregorianCalendar();
			GregorianCalendar cal2 = new GregorianCalendar();

			if (qcmForm.field("dateOuverture").value() != null) {
				cal.setTime(qcm.getDateOuverture());
				dateOuverture = Utile.dateToString(cal);
			}

			if (qcmForm.field("dateCloture").value() != null) {
				cal2.setTime(qcm.getDateCloture());
				dateFermeture = Utile.dateToString(cal2);
			}
			if (step == 1) {
//				System.out.println("Step 1_qcm : \n clé:"
//						+ qcm.getCleAuthentification() + "\n libelle:"
//						+ qcm.getLibelle() + "\n ID:" + qcm.getIdQcm()
//						+ "\n DateCloture:" + qcm.getDateCloture()
//						+ "\n DateCreation" + qcm.getDateCreation()
//						+ "\n DataOuverture:" + qcm.getDateOuverture()
//						+ "\n ListeQuestion:" + qcm.getListeQuestions()
//						+ "\n UserId:" + qcm.getUser().getIdUser()
//						+ "\n Statut:" + qcm.getStatut()
//						+ "\n ListeNiveauQuestions :"
//						+ qcm.getListeNiveauQuestions() + "\n");
				return ok(initiateQcm.render(qcmForm, dateOuverture,
						dateFermeture));
			}
			if (step == 2) {
				System.out.println("Step 2_qcm : \n clé:"
						+ qcm.getCleAuthentification() + "\n libelle:"
						+ qcm.getLibelle() + "\n ID:" + qcm.getIdQcm()
						+ "\n DateCloture:" + qcm.getDateCloture()
						+ "\n DateCreation" + qcm.getDateCreation()
						+ "\n DataOuverture:" + qcm.getDateOuverture()
						+ "\n ListeQuestion:" + qcm.getListeQuestions()
						+ "\n UserId:" + qcm.getUser().getIdUser()
						+ "\n Statut:" + qcm.getStatut()
						+ "\n ListeNiveauQuestions" + ":"
						+ qcm.getListeNiveauQuestions() + "\n");
				List<Theme> allThemes = Theme.findAll();
				
				return ok(associerQuestionQcm.render(qcmForm, qcm, allThemes));
			}
			if (step == 3) {
				System.out.println("Step 3_qcm : \n clé:"
						+ qcm.getCleAuthentification() + "\n libelle:"
						+ qcm.getLibelle() + "\n ID:" + qcm.getIdQcm()
						+ "\n DateCloture:" + qcm.getDateCloture()
						+ "\n DateCreation" + qcm.getDateCreation()
						+ "\n DataOuverture:" + qcm.getDateOuverture()
						+ "\n ListeQuestion:" + qcm.getListeQuestions()
						+ "\n UserId:" + qcm.getUser().getIdUser()
						+ "\n Statut:" + qcm.getStatut()
						+ "\n ListeNiveauQuestions" + ":"
						+ qcm.getListeNiveauQuestions() + "\n");
				return ok(notation.render(qcmForm, qcm));
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		// TODO : renvoyer un message d'erreur
		return forbidden();
	}

	/**
	 * Creation d'un objet qcm avec les donnees de la session dernier stade
	 */
	private static Qcm toQcm(Session session) throws ParseException {
		Qcm qcm = new Qcm();
		GregorianCalendar g = new GregorianCalendar();
		List<Question> listeQuestions = new ArrayList<Question>();
		Question question = new Question();

		qcm.setCleAuthentification(Utile.generateCle());
		qcm.setDateCreation(g.getTime());
		if (session.get("dateCloture") != null) {
			qcm.setDateCloture(Utile.stringToDate(session.get("dateCloture")));
		}
		if (session.get("dateOuverture") != null) {
			qcm.setDateOuverture(Utile.stringToDate(session
					.get("dateOuverture")));
		}
		qcm.setLibelle(session.get("libelle"));
		qcm.setListeQuestions(listeQuestions);

		long idUser = Long.parseLong(session().get("id"));
		User e = User.findById(idUser);
		qcm.setUser(e);

		List<Qcm> allqcm = Qcm.findAll();
		int size = allqcm.size();
		Qcm lastQcm = allqcm.get(size - 1);
		Long idQcmNew = lastQcm.getIdQcm() + 1;
		qcm.setIdQcm(idQcmNew);

		if (session.get("listeQuestions") != null && session.get("listeQuestions").length() > 0) {
			String listeIdQuestion = session.get("listeQuestions");
			listeIdQuestion = listeIdQuestion.replaceAll("\\s", "");
			String[] listeId = listeIdQuestion.split("#");
			for (int i = 0; i < listeId.length; i++) {
				long idQuestion = Long.parseLong(listeId[i]);
				listeQuestions.add(Question.findById(idQuestion));
			}
			qcm.setListeQuestions(listeQuestions);
		}
		qcm=updateQcmNiveauQuestion(session, qcm);
		return qcm;
	}
	
	private static Qcm updateQcmNiveauQuestion(Session session, Qcm qcm) throws ParseException {
		QcmNiveauQuestion tempFacile= new QcmNiveauQuestion();
		QcmNiveauQuestion tempMedium= new QcmNiveauQuestion();
		QcmNiveauQuestion tempDifficile= new QcmNiveauQuestion();
		QcmNiveauQuestion tempBonus= new QcmNiveauQuestion();
		List<QcmNiveauQuestion> listeNiveauQuestions= new ArrayList<QcmNiveauQuestion>();

		tempFacile.setNiveauQuestion(NiveauQuestion.findById(1L));
		tempMedium.setNiveauQuestion(NiveauQuestion.findById(2L));
		tempDifficile.setNiveauQuestion(NiveauQuestion.findById(3L));
		tempBonus.setNiveauQuestion(NiveauQuestion.findById(4L));
		
//		tempFacile.setPointNegatif(Long.parseLong(session.get("ppf")));
//		tempFacile.setPointPositif(Long.parseLong(session.get("pnf")));
//		tempMedium.setPointNegatif(Long.parseLong(session.get("ppm")));
//		tempMedium.setPointPositif(Long.parseLong(session.get("pnm")));	
//		tempDifficile.setPointNegatif(Long.parseLong(session.get("ppd")));
//		tempDifficile.setPointPositif(Long.parseLong(session.get("pnd")));	
//		tempBonus.setPointNegatif(Long.parseLong(session.get("ppb")));
//		tempBonus.setPointPositif(Long.parseLong(session.get("pnb")));
//		
//		listeNiveauQuestions.add(tempFacile);
//		listeNiveauQuestions.add(tempMedium);
//		listeNiveauQuestions.add(tempDifficile);
//		listeNiveauQuestions.add(tempBonus);

		qcm.setListeNiveauQuestions(listeNiveauQuestions);
		return qcm;
	}

	private static Map<String, String> toMap(Form<?> qcm, StringBuilder liste) {
		// Fill the form with data session
		Map<String, String> map = new HashMap<String, String>();
		map.put("libelle", qcm.field("libelle").valueOr(""));
		map.put("dateOuverture", qcm.field("dateOuverture").valueOr(""));
		map.put("dateCloture", qcm.field("dateCloture").valueOr(""));
		String listeIdQuestion = liste.toString();
		map.put("listeQuestions", listeIdQuestion);
		map.put("ppf",qcm.field("ppf").valueOr(""));
		map.put("pnf",qcm.field("pnf").valueOr(""));
		map.put("ppm",qcm.field("ppm").valueOr(""));
		map.put("pnm",qcm.field("pnm").valueOr(""));
		map.put("ppd",qcm.field("ppd").valueOr(""));
		map.put("pnd",qcm.field("pnd").valueOr(""));
		map.put("ppb",qcm.field("ppb").valueOr(""));
		map.put("pnb",qcm.field("pnb").valueOr(""));		
		return map;
	}

	/**
	 * Envoie de chaque partie de la creation du QCM
	 */
	public static Result submit(int step) {

		if (step == 1) {
			return handleStep1Submission();
		}
		if (step == 2) {
			return handleStep2Submission();
		} else {
			return handleStep3Submission();
		}
	}

	private static Result handleStep1Submission() {
		// TODO filledForm nous servira à vérifier que les données sont bon
		DynamicForm filledForm = form().bindFromRequest();
		StringBuilder listeQuestion = getUserChoseQuestion(session());
		session().putAll(toMap(filledForm, listeQuestion));
		System.out.println("Session Step1 :"+session().toString()+"\n ");
		return redirect(routes.CreateQCM.step(2));
	}

	private static StringBuilder getUserChoseQuestion(Session s) {
		Map<String, String[]> urlFormEncoded = request().body().asFormUrlEncoded();
		StringBuilder listQuestions = new StringBuilder();
		
		if(s.get("listeQuestions") != null && s.get("listeQuestions").length() > 0){
			System.out.println("liste des question"+s.get("listeQuestions"));
			listQuestions.append(s.get("listeQuestions"));
			return listQuestions;
		}
		if (urlFormEncoded != null) {
			for (String key : urlFormEncoded.keySet()) {
				String[] value = urlFormEncoded.get(key);
				// on selectionne liste de Question
				if (value.length > 1) {
					for (int i = 0; i < value.length; i++) {
						listQuestions.append(value[i] + "#");
					}
					listQuestions.deleteCharAt(listQuestions.length() - 1);
				}
			}
		}
		return listQuestions;
	}

	private static Result handleStep2Submission() {
		DynamicForm filledForm = form().bindFromRequest();
		StringBuilder listeQuestion = getUserChoseQuestion(session());
		if ("retour".equals(filledForm.field("action").value())) {
			return redirect(routes.CreateQCM.step(1));
		} else {
			session().putAll(toMap(filledForm, listeQuestion));
			System.out.println("Session Step2 :"+session().toString()+"\n ");
			return redirect(routes.CreateQCM.step(3));
		}
	}

	private static Result handleStep3Submission() {
		DynamicForm filledForm = form().bindFromRequest();
		if ("retour".equals(filledForm.field("action").value())) {
			return redirect(routes.CreateQCM.step(2));
		} else {
			StringBuilder listeQuestion = getUserChoseQuestion(session());
			session().putAll(toMap(filledForm, listeQuestion));
			System.out.println("Session Step3 :"+session().toString()+"\n ");
			
			Qcm created = null;
			try {
				created = toQcm(session());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			 //created.save();
			// Clear the session
			session().clear();
			 System.out.println("Step 2_qcm : \n clé:"
						+ created.getCleAuthentification() + "\n libelle:"
						+ created.getLibelle() + "\n ID:" + created.getIdQcm()
						+ "\n DateCloture:" + created.getDateCloture()
						+ "\n DateCreation" + created.getDateCreation()
						+ "\n DataOuverture:" + created.getDateOuverture()
						+ "\n ListeQuestion:" + created.getListeQuestions()
						+ "\n UserId:" + created.getUser().getIdUser()
						+ "\n Statut:" + created.getStatut()
						+ "\n ListeNiveauQuestions" + ":"
						+ created.getListeNiveauQuestions() + "\n");
			return ok(recupilatif.render(created));
		}
	}

	// private static Qcm buildResponse(DynamicForm filledForm) {
	// Qcm created = new Qcm();
	// created.setIdQcm(13L);
	// created.setCleAuthentification("toto");
	// try {
	// created.setDateCloture(Utile.stringToDate(filledForm
	// .get("dateCloture")));
	// } catch (ParseException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// GregorianCalendar g = new GregorianCalendar();
	// created.setDateCreation(g.getTime());
	// try {
	// created.setDateOuverture(Utile.stringToDate(filledForm
	// .get("dateOuverture")));
	// } catch (ParseException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// created.setLibelle(filledForm.get("libelle"));
	// created.setListeQuestions(null);
	// return created;
	// }

	public static Result getMatiere(int idtheme) {
		Theme t = new Theme();
		Long idL = (long) idtheme;
		t = Theme.findById(idL);
		List<Matiere> allMatiere = t.getSesMatieres();
		StringBuilder list = new StringBuilder();
		for (int i = 0; i < allMatiere.size(); i++) {
			Matiere m = allMatiere.get(i);
			list.append(m.getIdMatiere() + "#" + m.getLibelleM() + ";");
		}
		list.deleteCharAt(list.length() - 1);
		return ok(listeMatiere.render(list.toString()));
	}

	public static Result getChapitre(int idmatiere) {
		Matiere m = new Matiere();
		Long idL = (long) idmatiere;
		m = Matiere.findById(idL);
		List<Chapitre> allChapitre = m.getSesChapitres();
		StringBuilder list = new StringBuilder();
		for (int i = 0; i < allChapitre.size(); i++) {
			Chapitre c = allChapitre.get(i);
			list.append(c.getIdChapitre() + "#" + c.getLibelleC() + ";");
		}
		list.deleteCharAt(list.length() - 1);
		return ok(listeChapitre.render(list.toString()));
	}

	public static Result getQuestion(int idquestion) {
		Long idL = (long) idquestion;
		Chapitre c = new Chapitre();
		c = Chapitre.findById(idL);
		List<Question> allQuestion = c.getSesQuestions();
		StringBuilder list = new StringBuilder();
		for (int i = 0; i < allQuestion.size(); i++) {
			Question q = allQuestion.get(i);
			list.append(q.getIdQuestion() + "#" + q.getLibelleQuestion() + ";");
		}
		list.deleteCharAt(list.length() - 1);
		return ok(listeQuestion.render(list.toString()));
	}

	public static Result getCommentaire(int idquestion) {
		Long idL = (long) idquestion;
		Question q = new Question();
		q = Question.findById(idL);
		StringBuilder list = new StringBuilder();
		list.append(q.getLibelleQuestion() + ";" + q.getCommentaire() + ";"
				+ q.getNiveauQuestion().getLibelleNiveau() + ";");
		List<Choix> allChoix = q.getListeChoix();
		for (int i = 0; i < allChoix.size(); i++) {
			Choix c = allChoix.get(i);
			list.append(c.getDescriptifChoix() + "     Réponse : "
					+ c.getEstVrai() + "#");
		}
		list.deleteCharAt(list.length() - 1);
		return ok(commentaireQuestion.render(list.toString()));
	}
}